package com.mxchip.livestar

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.view.MotionEvent
import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import com.deeruu.system_help.Ethrenet
import com.trello.lifecycle2.android.lifecycle.AndroidLifecycle
import com.trello.rxlifecycle3.LifecycleProvider
import com.umeng.analytics.MobclickAgent
import com.mxchip.livestar.utils.FileLog
import com.mxchip.livestar.base.HideSystemUILifecycleAware
import com.mxchip.livestar.base.SystemData
import com.mxchip.livestar.base.toast
import com.mxchip.livestar.widget.voice.VolumeChangeObserver
import com.mxchip.livestar.original.AudioPlayer
import com.mxchip.livestar.original.LocalHDMIAudioUtil
import com.mxchip.livestar.repository.RoomClientRepository
import com.mxchip.livestar.rx.RxBus
import com.mxchip.livestar.rx.RxConstant
import com.mxchip.livestar.rx.RxSchedulersHelper
import com.mxchip.livestar.sound.LocalRingManagement
import com.mxchip.livestar.ui.dial.DialFragment
import com.mxchip.livestar.ui.wificamera.WifiCameraVideoFragment
import com.mxchip.livestar.update.UpdateInstance
import com.mxchip.livestar.utils.SPreference
import com.mxchip.livestar.utils.Utils
import com.videohigh.boegam.screenpush.AudioEncoderCallback
import com.videohigh.boegam.screenpush.ScreenPushManager
import com.videohigh.graham.SessionContext
import com.videohigh.graham.SampleSDK
import io.reactivex.Observable
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import q.rorbin.badgeview.QBadgeView
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.TimeUnit
import kotlin.system.exitProcess

class MainActivity : AppCompatActivity() {

    private val provider: LifecycleProvider<Lifecycle.Event> = AndroidLifecycle.createLifecycleProvider(this)

    // private var localResAudioPubObservable: Observable<Boolean>? = null
    private lateinit var localResVideoPubObservable: Observable<Boolean>
    private lateinit var callInEventObservable: Observable<SessionContext>
    private lateinit var outCameraNotifyObservable: Observable<Boolean>
    private lateinit var missedReminder: Observable<Boolean>
    private lateinit var registerSuccessNotifyObservable: Observable<Boolean>
    private lateinit var usbDeviceObservable: Observable<Boolean>
    // private lateinit var invitationEvent: InvitationEvent

    private lateinit var mVolumeChangeObserver: VolumeChangeObserver

    private var count = 0

    private val logger = FileLog.getLogger(MainActivity::class.java)

    // private var mAudioDummy: AudioDummy? = null

    // private val sampleSDK = SampleSDK.getInstance()

    private val mWifiCameraVideoFragment: Array<WifiCameraVideoFragment?> = arrayOfNulls(4)

    private val dialFragment: DialFragment by lazy {
        DialFragment()
    }

    private val updateInstance by lazy {
        UpdateInstance.getInstance(this)
    }

    private val disposable: Disposable by lazy {
        Observable.interval(0, 60 * 15.toLong(), TimeUnit.SECONDS)
//                .compose(provider.bindToLifecycle())
//                .observeOn(AndroidSchedulers.mainThread())
//                .doOnNext {
//                    if (!cameraToggleButton.isChecked && RoomClientRepository.state.value == RoomClientRepository.State.IDLE) {
//                        cameraToggleButton.performClick()
//                    }
//                }
                .compose(RxSchedulersHelper.io())
                .filter {
                    logger.info(SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA).format(Date()) +
                            "MainActivity::updateState: filter:${Utils.getTopActivity(applicationContext).contains("MainActivity")} ")
                    Utils.getTopActivity(applicationContext).contains("MainActivity")
                }
                .subscribe {
                    logger.info(SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA).format(Date()) + "MainActivity::updateState: Observable.interval: ")
                    upgradeCheck()
                }
    }

    private val notReadNumber by lazy {
        QBadgeView(this)
    }

    private val mAudioPlayer: AudioPlayer by lazy {
        AudioPlayer(this)
    }

    private val localHDMIAudioUtil: LocalHDMIAudioUtil by lazy {
        val obj = LocalHDMIAudioUtil()
        obj.setCallBack(callBack)
        obj
    }

    /*private val mHandler: Handler by lazy {
        MyHandler()
    }*/


    override fun onDestroy() {
        super.onDestroy()
        mAudioPlayer.stopPlayer()
        if (!disposable.isDisposed) {
            disposable.dispose()
        }
        RxBus.get().unregister(RxConstant.USB_DEVICE_NOTIFY, usbDeviceObservable)
        RxBus.get().unregister(RxConstant.CALL_IN_EVENT, callInEventObservable)
        RxBus.get().unregister(RxConstant.OUT_CAMERA_NOTIFY, outCameraNotifyObservable)
        RxBus.get().unregister(RxConstant.MISSED_REMINDER, missedReminder)
        RxBus.get().unregister(RxConstant.REGISTER_SUCCESS_NOTIFY_MAIN_ACTIVITY, registerSuccessNotifyObservable)
        LocalRingManagement.getInstance().release()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_main)
        lifecycleScope.launch {
            var first = loadAudioDevices()
            if (!first.isNullOrEmpty()) {
                Ethrenet.setExtUsbSoundMode(first,this@MainActivity)
            }
        }
        if (savedInstanceState == null) {
            supportFragmentManager.beginTransaction()
                    .replace(R.id.container_dial, dialFragment)
                    .commitNow()
        }

        mVolumeChangeObserver = VolumeChangeObserver(this)
//        mVolumeChangeObserver.volumeChangeListener = this
        val initVolume = mVolumeChangeObserver.currentMusicVolume
        Log.e(TAG, "initVolume = $initVolume")
        startBj01mHost()
        lifecycle.addObserver(HideSystemUILifecycleAware())
        notReadNumber.bindTarget(recentCallButton)
        notReadNumber.hide(true)

        // not_read_number.setDisplayDot(true)
        // not_read_number.setDotNum(0)
        // not_read_number.setDotVisable(false)

        // RoomClientRepository.init(SystemData.userId(), SystemData.deviceId(), SystemData.roomId(), SystemData.clientType)
        RoomClientRepository.connect()
        // SystemData.getInstance().sm_evthandle(Event.connect)

        initOnCreateRxBus()

        RoomClientRepository.isConnect.observe(this, androidx.lifecycle.Observer {
            val stateStr = if (it) getString(R.string.idle) else getString(R.string.not_online)
            val s = getString(R.string.state_str) + stateStr
            state.text = s
            updateInstance.setInstantInstall(it)
        })

        val dialog = AlertDialog.Builder(this).setTitle(getString(R.string.tips)).setMessage(getString(R.string.check_net)).setPositiveButton(getString(R.string.sure_str)) { _, _ ->
            RoomClientRepository.disconnect()
            RoomClientRepository.connect()
        }.setCancelable(false).create()

        RoomClientRepository.isConnect.observe(this@MainActivity, androidx.lifecycle.Observer {
            if (!it && !dialog.isShowing) {
                dialog.show()
            }
            if (it && dialog.isShowing) {
                dialog.dismiss()
            }
        })


        initTimer()

        setOnClick()

        mAudioPlayer.startPlayer()
        if (SPreference.isExtUsbAudioDevice())
            toast("已开启外置音频")
    }

    override fun onPause() {
        super.onPause()
        MobclickAgent.onPause(this) // 不能遗漏
        //解注册广播接收器
        mVolumeChangeObserver.unregisterReceiver()

        RxBus.get().unregister(RxConstant.RES_VIDEO_PUB_NOTIFY, localResVideoPubObservable)
        ScreenPushManager.getInstance().removeAudioEncoderCallback(audioEncoderCallback)
        // RxBus.get().unregister(RxConstant.LOCAL_RES_AUDIO_PUB, localResAudioPubObservable)
    }

    override fun onResume() {
        super.onResume()
        //获取wifi管理服务
        wifiapToggleButton.isChecked = Utils.isApEnabled(this)


        MobclickAgent.onResume(this) // 不能遗漏
        mVolumeChangeObserver.registerReceiver()
        val versionCodeStr = getString(R.string.version_str) + Utils.getVersionName(this)
        version_code.text = versionCodeStr
//        checkNotDisturb()
        initOnResumeRxBus()
        ScreenPushManager.getInstance().addAudioEncoderCallback(audioEncoderCallback)
    }

    private fun setOnClick() {
        //通过按钮事件设置热点
        wifiapToggleButton.setOnClickListener {
            //如果是打开状态就关闭，如果是关闭就打开
            val checked = wifiapToggleButton!!.isChecked
            if (checked) {
                toast(getString(R.string.wifi_close_tips))
            }
            Utils.setWifiApEnabled(checked, it.context)
        }


        dndToggleButton.isChecked = SPreference.getDoNotDisturbMode()
        dndToggleButton.setOnClickListener {
            val checked = dndToggleButton.isChecked
            if (checked) {
                toast(getString(R.string.only_receive_friend))
            }
            SPreference.setDoNotDisturbMode(checked)
        }

        cameraToggleButton.setOnCheckedChangeListener { _, isChecked ->
            SystemData.autoAnswer = isChecked
        }

        groupCallButton.setOnClickListener {
            Log.d(TAG, "jumpToGroupCallActivity: view:$it")
            Handler().postDelayed({
                val intent = Intent(this@MainActivity, GroupCallSelectionActivity::class.java)
                startActivity(intent)
            }, 100)
        }

        addressBookButton.setOnClickListener {
            Log.d(TAG, "jumpToAddressBookActivity: view:$it")
            Handler().postDelayed({
                val intent = Intent(this@MainActivity, AddressBookActivity::class.java)
                startActivity(intent)
            }, 100)
        }

        recentCallButton.setOnClickListener {
            Log.d(TAG, "jumpToRecentCallActivity: view:$it")
            Handler().postDelayed({
                // not_read_number.setDotNum(0)
                // not_read_number.setDotVisable(false)
                notReadNumber.hide(true)
                val intent = Intent(this@MainActivity, RecentCallActivity::class.java)
                startActivity(intent)
            }, 100)
        }

        setting.setOnClickListener {
            Log.d(TAG, "jumpToSettingActivity: view:$it")
            Handler().postDelayed({
                val intent = Intent(this@MainActivity, SettingsActivity::class.java)
                startActivity(intent)
            }, 100)
        }

        exit_text.setOnClickListener {
            Log.d(TAG, "exitWifiRes: view:$it")
            ScreenPushManager.getInstance().close()
            // ScreenPushNative.nativeMAINConnOpt(0, GeneralConst.JNI_STATUS_CLOSE_V)
        }

    }

    @SuppressLint("CheckResult")
    private fun initTimer() {
        val isAuthDialog = AlertDialog.Builder(this).setTitle(getString(R.string.tips)).setMessage(getString(R.string.pay_money)).create()
        Observable.interval(3, 60 * 60 * 24, TimeUnit.SECONDS)
                .compose(provider.bindToLifecycle())
                .subscribe {
                    lifecycleScope.launch {
                        checkState(isAuthDialog)
                    }
                }

        Observable.interval(1, TimeUnit.SECONDS)
                .compose(provider.bindToLifecycle())
                .compose(RxSchedulersHelper.io_main())
                .filter {
                    if (!Utils.getTopActivity(applicationContext).contains("MainActivity")) {
                        count = 0
                        val window = window
                        val lp = window.attributes
                        lp.screenBrightness = 1f
                        window.attributes = lp
                    }
                    Utils.getTopActivity(applicationContext).contains("MainActivity")
                }
                .subscribe {
                    count++
                    if (count > 30) {
                        val window = window
                        val lp = window.attributes
                        lp.screenBrightness = 0.1f
                        window.attributes = lp
                    }
                }
    }

    @SuppressLint("CheckResult")
    private fun initOnCreateRxBus() {
        missedReminder = RxBus.get().register(RxConstant.MISSED_REMINDER, Boolean::class.java)
        missedReminder.compose(provider.bindToLifecycle())
                .compose(RxSchedulersHelper.io_main()).subscribe(::missedReminderAdd) { error -> error.message?.let { toast(it) } }

        registerSuccessNotifyObservable = RxBus.get().register(RxConstant.REGISTER_SUCCESS_NOTIFY_MAIN_ACTIVITY, Boolean::class.java)
        registerSuccessNotifyObservable.compose(provider.bindToLifecycle())
                .compose(RxSchedulersHelper.io_main())
                .subscribe(::updateState) { error -> toast("initRxBus netStateObservable ${error.message}") }

        outCameraNotifyObservable = RxBus.get().register(RxConstant.OUT_CAMERA_NOTIFY, Boolean::class.java)
        outCameraNotifyObservable.compose(provider.bindToLifecycle())
                .compose(RxSchedulersHelper.io_main())
                .subscribe(::changeOutCameraState) { error -> toast("initRxBus showToastObservable error" + error.message) }

        //        if (invitationEventObservable != null) {
        //            RxBus.get().unregister(RxConstant.INVITATION_EVENT, invitationEventObservable)
        //        }

        callInEventObservable = RxBus.get().register(RxConstant.CALL_IN_EVENT, SessionContext::class.java)
        callInEventObservable.compose(provider.bindToLifecycle())
                .compose(RxSchedulersHelper.io_main()).subscribe(::onCallIn) { error -> toast("initRxBus jumpToCallActivity $error") }


        usbDeviceObservable = RxBus.get().register(RxConstant.USB_DEVICE_NOTIFY, Boolean::class.java)
        usbDeviceObservable.compose(RxSchedulersHelper.io_main()).subscribe(::usbDeviceChange) { error ->
            run {
                logger.error(SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA).format(Date()) +
                        " usbDeviceChange" + error.message)
                error.printStackTrace()
            }
        }
    }

    private fun usbDeviceChange(b: Boolean?) {
        lifecycleScope.launch {
            loadAudioDevices()
        }
    }

    private fun checkState(isAuthDialog: AlertDialog) {

        RoomClientRepository.getAuthInfo({data ->
            val isAuth = data.isValid
            if (!isAuth) {
                SystemData.globalIsAuth = false
                //                                        launch(Dispatchers.Main) {
                isAuthDialog.setCancelable(false)
                isAuthDialog.setButton(AlertDialog.BUTTON_POSITIVE, "重试") { _, _ -> checkState(isAuthDialog) }
                isAuthDialog.show()

            } else {
                SystemData.globalIsAuth = true
            }

        } , { code, message ->
            logger.error("MainActivity::checkState authTermDevice ApiErrorResponse code $code resp $message")
            isAuthDialog.setMessage("请求错误:${message}")
            isAuthDialog.setButton(AlertDialog.BUTTON_POSITIVE, "重试") { _, _ -> checkState(isAuthDialog) }

        })
    }

    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        count = 0
        val window = window
        val lp = window.attributes
        lp.screenBrightness = 1f
        window.attributes = lp
        return super.dispatchTouchEvent(ev)
    }

    @SuppressLint("CheckResult")
    private fun initOnResumeRxBus() {
        //开启关闭 无线投屏按钮
        localResVideoPubObservable = RxBus.get().register(RxConstant.RES_VIDEO_PUB_NOTIFY, Boolean::class.java)
        localResVideoPubObservable.compose(provider.bindToLifecycle()).compose(RxSchedulersHelper.io_main())
                .subscribe(::localResVideoPubObservable) { error -> error.printStackTrace() }

      /*  // 接通回调
        localResAudioPubObservable = RxBus.get().register(RxConstant.LOCAL_RES_AUDIO_PUB, Boolean::class.java)
        localResAudioPubObservable?.compose(provider.bindToLifecycle())?.compose(RxSchedulersHelper.io_main())
                ?.subscribe(::busyResAudioPubCloseObservable) { error -> error.printStackTrace() }*/
    }

    /*private val audioResDataCallBack: AudioResDataCallBack = object : AudioResDataCallBack {
        override fun onGetPcmFrame(data: ByteArray, length: Int) {
            if (data.isEmpty()) {
                return
            }
            val localPlay = ByteArray(640)
            System.arraycopy(data, 0, localPlay, 0, length)
            localHDMIAudioUtil.putData(localPlay)
        }
    }*/


    private fun handleOnGetPcmFrame(data: ByteArray, length: Int) {
        if (data.isEmpty()) {
            return
        }
        val localPlay = ByteArray(640)
        System.arraycopy(data, 0, localPlay, 0, length)
        localHDMIAudioUtil.putData(localPlay)
    }

    private val callBack: LocalHDMIAudioUtil.PlayLocalHDMIAudioCallBack = LocalHDMIAudioUtil.PlayLocalHDMIAudioCallBack { data ->
        mAudioPlayer.addAudioData(data)
    }

    /*private fun busyResAudioPubCloseObservable(aBoolean: Boolean) {
        if (aBoolean) {
            localHDMIAudioUtil.setCallBack(callBack)
            if (mAudioDummy == null) {
                mAudioDummy = AudioDummy()
                mAudioDummy?.setAudioResDataCallBack(audioResDataCallBack)
                mAudioDummy?.start_audio_dummy_thread()
            }
        } else {
            if (mAudioDummy != null) {
                mAudioDummy?.setAudioResDataCallBack(null)
                mAudioDummy?.stop_audio_dummy_thread()
                mAudioDummy = null
            }
            localHDMIAudioUtil.setCallBack(null)
        }
    }*/

    private fun localResVideoPubObservable(aBoolean: Boolean) {
        if (aBoolean) {
            SystemData.getInstance().wifiResPub = true
            mWifiCameraVideoFragment[0] = WifiCameraVideoFragment.newInstance(0)
            showFragment(mWifiCameraVideoFragment[0])

            setViewVisibility(View.GONE)
            exit_text.visibility = View.VISIBLE
            supportFragmentManager.beginTransaction().hide(dialFragment).commit()
        } else {
            supportFragmentManager.beginTransaction().show(dialFragment).commit()
            setViewVisibility(View.VISIBLE)
            exit_text.visibility = View.GONE

            SystemData.getInstance().wifiResPub = false
            if (mWifiCameraVideoFragment[0] != null) {
                removeFragment(mWifiCameraVideoFragment[0])
                mWifiCameraVideoFragment[0] = null
            }
        }
    }

    private fun setViewVisibility(visibility: Int) {
        setting!!.visibility = visibility
        groupCallButton.visibility = visibility
        addressBookButton.visibility = visibility
        recentCallButton.visibility = visibility
        wifiapToggleButton.visibility = visibility
        cameraToggleButton.visibility = visibility
    }


    private fun missedReminderAdd(aBoolean: Boolean) {
        Log.d(TAG, "missedReminderAdd: aBoolean:${aBoolean}")
        /*if (!not_read_number.dotVisible) {
            not_read_number.setDotVisable(true)
        }*/
        // val dotNum = not_read_number.badgeNumber

        notReadNumber.badgeNumber += 1

        /*not_read_number.setBadgeNumber()
        if (dotNum == "99+") {
        } else {
            val i = dotNum.toInt()
            not_read_number.setDotNum(i + 1)
        }*/
    }

    override fun onBackPressed() {
        super.onBackPressed()
        exitProcess(0)
    }

    @SuppressLint("CheckResult")
    private fun updateState(aBoolean: Boolean) {
        Log.d(TAG, "updateState: aBoolean:${aBoolean}")
        val versionCodeStr = getString(R.string.version_str) + Utils.getVersionName(this)
        version_code.text = versionCodeStr
        disposable.isDisposed
    }

    private fun upgradeCheck() {
        updateInstance.autoCheck(this)
    }

    private fun startBj01mHost() {
        Log.i(TAG, "startBj01mHost")
        ScreenPushManager.getInstance().init()
        ScreenPushManager.getInstance().setCallback(screenPushCallback)

        // ScreenPushNative.SetHandler(mHandler)
    }


    val audioEncoderCallback = AudioEncoderCallback { data, length -> handleOnGetPcmFrame(data, length) }


    private fun onCallIn(sessionContext: SessionContext) {

        Log.e("inviteNotifyJson", sessionContext.toString())
        if (Utils.getTopActivity(applicationContext).contains("CallActivityA")) {
            return
        }
        /*val termNumbers = event.invitationNumbers.map {
            "${it.roomId}#${it.termId}"
        }

        if (!termNumbers.contains("${SystemData.roomId()}#${SystemData.userId()}")) {
            return
        }*/

        // invitationEvent = event
        if (SystemData.getInstance().wifiResPub) {
            // ScreenPushNative.nativeMAINConnOpt(0, GeneralConst.JNI_STATUS_CLOSE_V)
            ScreenPushManager.getInstance().close()
            logger.info(SimpleDateFormat("yyyy-MM-dd-HH:mm:ss", Locale.CHINA).format(Date())
                    + " SystemData.getInstance().wifiResPub jumpToAnswerActivity")
            jumpToAnswerActivity(sessionContext)
        } else {
            val dndMode = SPreference.getDoNotDisturbMode()
            if (!SystemData.globalIsAuth) {
                logger.info("SystemData.globalIsAuth is false "
                        + SimpleDateFormat("yyyy-MM-dd-HH:mm:ss", Locale.CHINA).format(Date()) + " activeHangUp")
            } else if (!dndMode) {
                logger.info(SimpleDateFormat("yyyy-MM-dd-HH:mm:ss", Locale.CHINA).format(Date())
                        + " RxConstant.INVITATION_TO_NOTICE_OBSERVABLE jumpToAnswerActivity")
                jumpToAnswerActivity(sessionContext)
            } else {
                logger.info("globalIsAuth and dndMode are all true "
                        + SimpleDateFormat("yyyy-MM-dd-HH:mm:ss", Locale.CHINA).format(Date()) + " activeHangUp")
            }
        }
    }

    private fun changeOutCameraState(aBoolean: Boolean) {
        Log.d(TAG, "changeOutCameraState: aBoolean:${aBoolean}")
    }

    /**
     * 跳转到等待接听界面
     *
     * @param invitationEvent server data
     */
    private fun jumpToAnswerActivity(sessionContext: SessionContext) {
        statisticActiveUser()
        logger.info("$TAG::jumpToAnswerActivity: $sessionContext")
        CallActivityA.open(this, sessionContext)
    }

    private fun statisticActiveUser() {
        val userName: MutableMap<String, Any> = HashMap()
        userName["name"] = SystemData.userId()
        MobclickAgent.onEventObject(this, "user_name", userName)
    }


    private val screenPushCallback = object: ScreenPushManager.ScreenPushCallback {

        /*override fun onPlayerCreate() {
            RxBus.get().post(RxConstant.LOCAL_RES_AUDIO_PUB, true)
        }

        override fun onPlayerDestroy() {
            RxBus.get().post(RxConstant.BUSY_RES_AUDIO_PUB, false)
            RxBus.get().post(RxConstant.LOCAL_RES_AUDIO_PUB, false)
        }*/

        override fun onVideoStart() {
            if (Utils.isFastClick()) {
                ScreenPushManager.getInstance().close()
                // ScreenPushNative.nativeMAINConnOpt(0, GeneralConst.JNI_STATUS_CLOSE_V)
                return
            }

            if (!RxBus.get().isHasObservable(RxConstant.RES_VIDEO_PUB_NOTIFY)) {
                ScreenPushManager.getInstance().close()
                // ScreenPushNative.nativeMAINConnOpt(0, GeneralConst.JNI_STATUS_CLOSE_V)
                return
            }

            RxBus.get().post(RxConstant.RES_VIDEO_PUB_NOTIFY, true)
        }

        override fun onVideoStop() {
            RxBus.get().post(RxConstant.RES_VIDEO_PUB_NOTIFY, false)
        }
    }

    /*
    private class MyHandler : Handler() {
        val encoderRcBbr = 56 // val ENCODER_RC_CQP = 57 // val ENCODER_RC_CRF = 55
        val encoder1080 = 5
//         val ENCODER_720 = 6
        override fun handleMessage(paramMessage: Message) {
            when (paramMessage.what) {
                GeneralConst.SV_HD_CREATE_PLAYER_NTFY -> {
                    RxBus.get().post(RxConstant.LOCAL_RES_AUDIO_PUB, true)
                    Log.d(TAG, "SV_HD_CREATE_PLAYER_NTFY")
                }
                GeneralConst.SV_HD_DESTROY_PLAYER_NTFY -> {
                    RxBus.get().post(RxConstant.BUSY_RES_AUDIO_PUB, false)
                    RxBus.get().post(RxConstant.LOCAL_RES_AUDIO_PUB, false)
                    Log.d(TAG, "SV_HD_DESTROY_PLAYER_NTFY")
                }
                GeneralConst.SV_HD_CONN_ONLINE_STATE -> {
                    val connId = paramMessage.arg1
                    val stat = paramMessage.arg2
                    val ipAddr = paramMessage.obj as? String
                    ScreenPushNative.nativeResetConnectEncoder(0, encoder1080, 15, 30, encoderRcBbr, 1024*3/2)
                    Log.d(TAG, "SV_HD_CONN_ONLINE_STATE:connId:$connId,stat:$stat,ipAddr:$ipAddr")
                }
                GeneralConst.SV_HD_CONN_DEVICE_NAME -> {
                    val connId = paramMessage.arg1
                    val hostName = paramMessage.obj as String
                    Log.d(TAG, "SV_HD_CONN_DEVICE_NAME: connId=$connId,HostName=$hostName")
                    ScreenPushNative.nativeResetConnectEncoder(0, encoder1080, 15, 30, encoderRcBbr, 1024*3/2)
                }
                GeneralConst.SV_HD_CONN_VIDEO_START -> {
                    val videoId = paramMessage.arg1
                    paramMessage.arg2
                    when (videoId) {
                        0 -> {
                            if (Utils.isFastClick()) {
                                ScreenPushNative.nativeMAINConnOpt(0, GeneralConst.JNI_STATUS_CLOSE_V)
                                return
                            }

                            if (!RxBus.get().isHasObservable(RxConstant.RES_VIDEO_PUB_NOTIFY)) {
                                ScreenPushNative.nativeMAINConnOpt(0, GeneralConst.JNI_STATUS_CLOSE_V)
                                return
                            }

                            RxBus.get().post(RxConstant.RES_VIDEO_PUB_NOTIFY, true)
                        }
                    }
                    Log.d(TAG, "SV_HD_CONN_VIDEO_START")
                }
                GeneralConst.SV_HD_CONN_VIDEO_STOP -> {
                    RxBus.get().post(RxConstant.RES_VIDEO_PUB_NOTIFY, false)
                    Log.d(TAG, "SV_HD_CONN_VIDEO_STOP")
                }
                GeneralConst.SV_HD_CONN_AUDIO_START -> {
                    val connId = paramMessage.arg1
                    val videoId = paramMessage.arg2
                    Log.d(TAG, "SV_HD_CONN_AUDIO_START:videoId=$videoId,connId=$connId")
                }
                GeneralConst.SV_HD_CONN_AUDIO_STOP -> {
                    val connId = paramMessage.arg1
                    val videoId = paramMessage.arg2
                    Log.d(TAG, "SV_HD_CONN_AUDIO_STOP:videoId=$videoId,connId=$connId")
                }
                GeneralConst.SV_HD_VIDEO_RESOLUTION_CHANGED -> {
                    val videoId = paramMessage.obj as Int
                    val width = paramMessage.arg1
                    val height = paramMessage.arg2
                    Log.d(TAG, "SV_HD_VIDEO_RESOLUTION_CHANGED: videoId=" + videoId + ",res=" + width + "x" + height)
                }
                GeneralConst.SV_HD_VIDEO_SHARED_DEVICE_NAME -> {
                    val videoId = paramMessage.arg1
                    val hostName = paramMessage.obj as String
                    Log.d(TAG, "SV_HD_VIDEO_SHARED_DEVICE_NAME:videoId=$videoId,HostName=$hostName")
                }
                GeneralConst.SV_HD_CONN_RESET_ENCODER_RESULT -> {
                    val connId = paramMessage.arg1
                    val result = paramMessage.arg2
                    Log.d(TAG, "SV_HD_CONN_RESET_ENCODER_RESULT: connId=$connId,result=$result")
                }
                GeneralConst.SV_HD_CONN_RESET_ENCODER -> {

                    Log.d(TAG, "SV_HD_CONN_RESET_ENCODER")
                }
            }
        }
    }*/

    private fun showFragment(newFragment: Fragment?) {
        val transaction = supportFragmentManager.beginTransaction()
        transaction.add(R.id.video_container0, newFragment!!)
        transaction.commit()
    }

    private fun removeFragment(newFragment: Fragment?) {
        val transaction = supportFragmentManager.beginTransaction()
        transaction.remove(newFragment!!)
        transaction.commit()
    }

//    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            return true
//        }
//        return super.onKeyDown(keyCode, event)
//    }

    companion object {
        private const val TAG = "MainActivity"
    }


    private suspend fun loadAudioDevices(): String? {
        val extAudio = arrayListOf<String>();
        withContext(Dispatchers.IO) {
            extAudio.clear()
            extAudio.addAll(Ethrenet.getAudioDevice())
            val first = extAudio.firstOrNull { !it.contains("Sabine") }
            Log.d(TAG, "loadAudioDevices: $first")
            if (first.isNullOrEmpty()) {
                SPreference.setExtUsbAudioDevice(false)
            } else {
                SPreference.setExtUsbAudioDevice(true)
                return@withContext first
            }

        }

        return null
    }
}